package com.we.flink.accountproxyuserlabelplatform.tag;

import org.apache.flink.api.common.functions.FilterFunction;
import org.apache.flink.api.common.functions.RichFlatMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.util.Collector;

import com.alibaba.fastjson.JSONObject;
import com.we.flink.accountproxyuserlabelplatform.table.TableUserLoan;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TagUserLoan {
    public long account_user_key;
    public int is_first_loan;

    public static Logger LOG = LoggerFactory.getLogger(TagUserLoan.class);

    public TagUserLoan(long account_user_key, int is_first_loan) {
        this.account_user_key = account_user_key;
        this.is_first_loan = is_first_loan;
    }

    public static TagUserLoan init(long account_user_key) {
        return new TagUserLoan(account_user_key, 1);
    }

    public static SingleOutputStreamOperator<String> getFlatMapStream(
            StreamTableEnvironment tableEnv, StreamExecutionEnvironment env) {

        Table tableRes = tableEnv.sqlQuery(TableUserLoan.QUERYSQL);
        DataStream<Tuple2<Boolean, TableUserLoan>> inputStream =
                tableEnv.toRetractStream(tableRes, TableUserLoan.class);

        SingleOutputStreamOperator<String> out =
                inputStream
                        .filter(
                                new FilterFunction<Tuple2<Boolean, TableUserLoan>>() {
                                    @Override
                                    public boolean filter(Tuple2<Boolean, TableUserLoan> value)
                                            throws Exception {
                                        return value.f0;
                                    }
                                })
                        .uid("TagUserLoan-proxy-filter")
                        .keyBy(
                                new KeySelector<Tuple2<Boolean, TableUserLoan>, Long>() {
                                    @Override
                                    public Long getKey(Tuple2<Boolean, TableUserLoan> value)
                                            throws Exception {
                                        return value.f1.getAccount_user_key();
                                    }
                                })
                        .flatMap(
                                new RichFlatMapFunction<Tuple2<Boolean, TableUserLoan>, String>() {
                                    ValueState<TagUserLoan> userLoanVState;

                                    @Override
                                    public void open(Configuration parameters) throws Exception {
                                        userLoanVState =
                                                getRuntimeContext()
                                                        .getState(
                                                                new ValueStateDescriptor<
                                                                        TagUserLoan>(
                                                                        "userLoanVState-proxy",
                                                                        TagUserLoan.class));
                                    }

                                    @Override
                                    public void flatMap(
                                            Tuple2<Boolean, TableUserLoan> value,
                                            Collector<String> out)
                                            throws Exception {
                                        final int is_first_loan = 0;
                                        long account_user_key = value.f1.getAccount_user_key();
                                        int account_report_status =
                                                (int) value.f1.getAccount_report_status();

                                        TagUserLoan tmpState = userLoanVState.value();
                                        TagUserLoan curState =
                                                tmpState == null
                                                        ? TagUserLoan.init(account_user_key)
                                                        : tmpState;

                                        /**
                                         * is_first_loan = 1 表示首贷用户 account_report_status == 2
                                         * 表示非首贷用户，即is_first_loan = 0
                                         */
                                        if (curState.getIs_first_loan() != 0
                                                && account_report_status == 2) {
                                            curState.is_first_loan = is_first_loan;

                                            JSONObject jsonObject = new JSONObject();
                                            jsonObject.put("account_user_key", account_user_key);
                                            jsonObject.put("is_first_loan", is_first_loan);

                                            userLoanVState.update(curState);
                                            out.collect(jsonObject.toString());
                                        }
                                    }
                                });
        return out;
    }

    public long getAccount_user_key() {
        return account_user_key;
    }

    public int getIs_first_loan() {
        return is_first_loan;
    }
}
